package com.benjamin.sinamicroblogclient;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.benjamin.common.ImageUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class StatusListAdapter extends ArrayAdapter<Status> {

	Context ctx;

	public StatusListAdapter(Context context, List<Status> statusList) {
		super(context, 0, statusList);

		ctx = context;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		StatusViewWrapper viewWrapper = null;

		if (rowView == null) {
			LayoutInflater inflater = LayoutInflater.from(ctx);
			rowView = inflater.inflate(R.layout.statusretweeted, null);

			viewWrapper = new StatusViewWrapper(rowView);
			rowView.setTag(viewWrapper);
		} else {
			viewWrapper = (StatusViewWrapper) rowView.getTag();
		}

		Status status = (Status) this.getItem(position);

		ImageView imageView = viewWrapper.getImageViewProfile();
		try {
			imageView.setImageDrawable(ImageUtils.getImage(status.getUser()
					.getProfileImageURL()));
		} catch (IOException e) {
			e.printStackTrace();
		}

		TextView tvScreenName = viewWrapper.getTextViewScreenName();
		tvScreenName.setText(status.getUser().getScreenName());

		TextView tvCreatedAt = viewWrapper.getTextViewCreatedAt();
		Date date = status.getCreatedAt();

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm");
		tvCreatedAt.setText(simpleDateFormat.format(date));

		TextView tvText = viewWrapper.getTextViewText();
		tvText.setText(status.getText());

		Status retweetedStatus = status.getRetweetedStatus();
		TextView tvTextRetweeted = viewWrapper.getTextViewTextRetweeted();
		if (retweetedStatus != null) {
			tvTextRetweeted.setText("@"
					+ retweetedStatus.getUser().getScreenName() + ": "
					+ retweetedStatus.getText());
		} else {
			tvTextRetweeted.setText("");
		}

		return rowView;
	}
}
